package com.aletto.general_store.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.presenters.core.SimpleParamsTemplate;
import com.aletto.general_store.utils.XHelper;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.Debounce;
import com.sisyphus.spinach.network.views.ToastView;
import com.sisyphus.spinach.utils.watchers.EmptyRule;
import com.sisyphus.spinach.utils.watchers.TextWatchers;

/**
 * 用户签名
 */
public class UserSignActivity extends AppCompatActivity {

    public static Intent newIntent(Context context, String id) {
        Intent intent = new Intent(context, UserSignActivity.class);
        intent.putExtra("ID", id);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_sign);
        XHelper.initTitle(this, R.string.title_update_sign);

        View tvSave = findViewById(R.id.tv_save);
        EditText etSign = findViewById(R.id.et_sign);
        TextWatchers.add(new EmptyRule(etSign)).setWatcherCallback(tvSave::setEnabled);

        // 修改签名
        Intent intent = getIntent();
        String id = intent.getStringExtra("ID");
        tvSave.setOnClickListener(v -> template.setParams(id).execute(getLifecycle()));
    }

    private final SimpleParamsTemplate<Object, String> template = new SimpleParamsTemplate<>() {

        @Override
        public INetTask.View<Object> view() {
            View tv_save = findViewById(R.id.tv_save);
            return new Debounce<>(tv_save,
                    new ToastView<>(tv_save.getContext(),
                            new INetTask.View<>() {
                                @Override
                                public void success(Object data) {
                                    finish();
                                }
                            }
                    )
            );
        }

        @Override
        public INetTask.Presenter<Object, INetTask.View<Object>> presenter() {
            EditText etSign = findViewById(R.id.et_sign);
            return new NetSingleTask<>(DataRepository.getInstance()
                    .updateUserDetails(
                            params[0],
                            null,
                            null,
                            etSign.getText().toString()
                    )
            );
        }
    };

}
